using System;
using System.Collections.Generic;
using System.Text;
using ClientTools.Library.DataTypes.Logging;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using Log=ClientTools.Library.DataTypes.Logging.Log;

namespace ClientTools.Library.Manager
{
    public static class LogManager 
    {
        private static ISqlHelper SqlHelper
        {
            get { return Application.SqlHelper; }
        }

        public static LogInfoCollection GetLogInfos()
        {
            var returnValue = new LogInfoCollection();
            using (var datareader = SqlHelper.ExecuteReader("SELECT logHeader, Count(*) ANZ FROM umbracoLog GROUP BY logHeader ORDER BY logHeader"))
                while (datareader.Read())
                    returnValue.Add(new LogInfo {LogHeader = datareader.GetString("logHeader"), Count = datareader.GetInt("ANZ")});
            return returnValue;
        }

        public static int DeleteLogsByDate(DateTime dat)
        {
            return SqlHelper.ExecuteNonQuery("DELETE FROM umbracoLog WHERE Datestamp < @dat", SqlHelper.CreateParameter("@dat", dat));
        }

        public static int DeleteLogsByHeader(string header)
        {
            return SqlHelper.ExecuteNonQuery("DELETE FROM umbracoLog WHERE logHeader = @logheader", SqlHelper.CreateParameter("@logheader", header));
        }

        public static int DeleteLogsByIDs(int[] logIds)
        {
            if (logIds.Length == 0)
                return 0;
            if (logIds.Length == 1)
                return SqlHelper.ExecuteNonQuery("DELETE FROM umbracoLog WHERE id = @id", SqlHelper.CreateParameter("@id", logIds[0]));

            var sb = new StringBuilder();
            foreach (var i in logIds)
                sb.AppendFormat(",{0}", i);
            return SqlHelper.ExecuteNonQuery(string.Format("DELETE FROM umbracoLog WHERE id IN ({0})", sb.ToString().Substring(1)));
        }

        public static LogCollection GetLogs(DateTime? dateStart, DateTime? dateEnd, string logHeader, int? userId, int? nodeId, int? maxRows, string comment)
        {
            var pars = new List<IParameter>();
                
            var sel = new StringBuilder();
            var where = new StringBuilder();
            sel.AppendFormat("SELECT TOP ({0}) id, userId, NodeId, Datestamp, logHeader, logComment FROM umbracoLog ", maxRows);

            if (logHeader != null && logHeader.Trim() != "")
            {
                where = where.Append(" AND logHeader = @logHeader");
                pars.Add(SqlHelper.CreateParameter("@logHeader", logHeader));
            }

            if (userId.HasValue)
            {
                where = where.Append(" AND userid = @userid");
                pars.Add(SqlHelper.CreateParameter("@userid", userId.Value));
            }

            if (nodeId.HasValue)
            {
                where = where.Append(" AND NodeID = @NodeID");
                pars.Add(SqlHelper.CreateParameter("@NodeID", nodeId.Value));
            }

            if (dateStart.HasValue)
            {
                where = where.Append(" AND Datestamp > @DateStart");
                pars.Add(SqlHelper.CreateParameter("@DateStart", dateStart.Value));
            }

            if (dateEnd.HasValue)
            {
                where = where.Append(" AND Datestamp < @DateEnd");
                pars.Add(SqlHelper.CreateParameter("@DateEnd", dateEnd.Value));
            }

            if (!comment.IsTrimmedNullOrEmpty())
                where.AppendFormat(" AND LogComment LIKE '%{0}%'", comment);

            var commandText = where.Length == 0
                                  ? string.Concat(sel.ToString(), " ORDER BY DateStamp DESC")
                                  : string.Concat(sel.ToString(), " WHERE ", where.ToString().Substring(4),
                                                  " ORDER BY DateStamp DESC");

            try
            {
                return GetLogsFromDatareader(SqlHelper.ExecuteReader(commandText, pars.ToArray()));
            }
            catch (Exception)
            {
                commandText = commandText.Replace("(", "").Replace(")", "");
                return GetLogsFromDatareader(SqlHelper.ExecuteReader(commandText, pars.ToArray()));
            }
        }

        private static LogCollection GetLogsFromDatareader(IRecordsReader datareader)
        {
            var returnValue = new LogCollection();

            while (datareader.Read())
                returnValue.Add(new Log
                                    {
                                        Id = datareader.GetInt("id"),
                                        UserId = datareader.GetInt("userId"),
                                        NodeId = datareader.GetInt("NodeId"),
                                        DateStamp = datareader.GetDateTime("Datestamp"),
                                        LogHeader = datareader.GetString("logHeader"),
                                        LogComment = datareader.GetString("logComment")
                                    });
            return returnValue;
        }
    }
}